<template>
  <div class="notification-test">
    <div class="test-header">
      <h2>系统通知测试</h2>
      <p>测试各种类型的系统通知功能</p>
    </div>

    <div class="test-content">
      <!-- 系统消息列表 -->
      <div class="section">
        <h3>系统消息列表</h3>
        <el-button @click="loadSystemMessages" type="primary">获取系统消息</el-button>
        <el-button @click="loadUnreadCount" type="info">获取未读数量</el-button>
        
        <div class="result-box">
          <h4>未读消息数量：{{ unreadCount }}</h4>
          
          <div v-if="systemMessages.length > 0" class="message-list">
            <div 
              v-for="message in systemMessages" 
              :key="message.messageId"
              class="message-item"
              :class="{ unread: !message.isRead }"
            >
              <div class="message-header">
                <span class="message-title">{{ message.title }}</span>
                <span class="message-time">{{ formatTime(message.createTime) }}</span>
                <el-tag :type="getTypeColor(message.type)" size="small">{{ message.type }}</el-tag>
              </div>
              <div class="message-content">{{ message.content }}</div>
              <div class="message-actions">
                <el-button 
                  v-if="!message.isRead" 
                  @click="markAsRead(message.messageId)" 
                  size="small"
                >
                  标记已读
                </el-button>
                <el-button 
                  v-if="message.actionUrl" 
                  @click="handleAction(message)" 
                  size="small" 
                  type="primary"
                >
                  {{ message.actionText || '查看详情' }}
                </el-button>
              </div>
            </div>
          </div>
          
          <div v-else class="empty-state">
            <p>暂无系统消息</p>
          </div>
        </div>
      </div>

      <!-- 发送测试通知 -->
      <div class="section">
        <h3>发送测试通知</h3>
        <el-form :model="testForm" label-width="120px">
          <el-form-item label="通知类型">
            <el-select v-model="testForm.type" placeholder="选择通知类型">
              <el-option label="合同通知" value="contract" />
              <el-option label="预约通知" value="appointment" />
              <el-option label="房源审核" value="house" />
              <el-option label="系统公告" value="announcement" />
            </el-select>
          </el-form-item>
          <el-form-item label="消息标题">
            <el-input v-model="testForm.title" placeholder="输入消息标题" />
          </el-form-item>
          <el-form-item label="消息内容">
            <el-input 
              v-model="testForm.content" 
              type="textarea" 
              :rows="3"
              placeholder="输入消息内容" 
            />
          </el-form-item>
          <el-form-item>
            <el-button @click="sendTestNotification" type="primary">发送测试通知</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 操作日志 -->
      <div class="section">
        <h3>操作日志</h3>
        <div class="log-box">
          <div v-for="(log, index) in logs" :key="index" class="log-item">
            <span class="log-time">{{ log.time }}</span>
            <span class="log-content">{{ log.content }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  getSystemMessages, 
  getSystemUnreadCount, 
  markSystemMessageRead 
} from '@/utils/apiService'

// 响应式数据
const systemMessages = ref([])
const unreadCount = ref(0)
const logs = ref([])

const testForm = ref({
  type: 'contract',
  title: '测试通知标题',
  content: '这是一条测试通知内容'
})

// 添加日志
const addLog = (content) => {
  logs.value.unshift({
    time: new Date().toLocaleTimeString(),
    content
  })
  if (logs.value.length > 20) {
    logs.value = logs.value.slice(0, 20)
  }
}

// 加载系统消息
const loadSystemMessages = async () => {
  try {
    addLog('开始获取系统消息列表...')
    const response = await getSystemMessages({ page: 1, size: 20 })
    
    console.log('🔍 系统消息响应:', response)
    
    const responseData = response.data
    if (responseData.code === 200 || responseData.code === '200') {
      systemMessages.value = responseData.data.messages || []
      addLog(`获取系统消息成功，共 ${systemMessages.value.length} 条`)
      ElMessage.success('获取系统消息成功')
    } else {
      addLog(`获取系统消息失败: ${responseData.message}`)
      ElMessage.error('获取系统消息失败: ' + responseData.message)
    }
  } catch (error) {
    addLog(`获取系统消息错误: ${error.message}`)
    ElMessage.error('获取系统消息失败')
    console.error('获取系统消息失败:', error)
  }
}

// 加载未读数量
const loadUnreadCount = async () => {
  try {
    addLog('开始获取未读消息数量...')
    const response = await getSystemUnreadCount()
    
    console.log('🔍 未读数量响应:', response)
    
    const responseData = response.data
    if (responseData.code === 200 || responseData.code === '200') {
      unreadCount.value = responseData.data.unreadCount || 0
      addLog(`获取未读数量成功: ${unreadCount.value}`)
      ElMessage.success('获取未读数量成功')
    } else {
      addLog(`获取未读数量失败: ${responseData.message}`)
      ElMessage.error('获取未读数量失败: ' + responseData.message)
    }
  } catch (error) {
    addLog(`获取未读数量错误: ${error.message}`)
    ElMessage.error('获取未读数量失败')
    console.error('获取未读数量失败:', error)
  }
}

// 标记消息为已读
const markAsRead = async (messageId) => {
  try {
    addLog(`标记消息 ${messageId} 为已读...`)
    const response = await markSystemMessageRead(messageId)
    
    console.log('🔍 标记已读响应:', response)
    
    const responseData = response.data
    if (responseData.code === 200 || responseData.code === '200') {
      // 更新本地状态
      const message = systemMessages.value.find(m => m.messageId === messageId)
      if (message) {
        message.isRead = true
      }
      unreadCount.value = Math.max(0, unreadCount.value - 1)
      
      addLog(`消息 ${messageId} 标记已读成功`)
      ElMessage.success('标记已读成功')
    } else {
      addLog(`标记已读失败: ${responseData.message}`)
      ElMessage.error('标记已读失败: ' + responseData.message)
    }
  } catch (error) {
    addLog(`标记已读错误: ${error.message}`)
    ElMessage.error('标记已读失败')
    console.error('标记已读失败:', error)
  }
}

// 处理消息操作
const handleAction = (message) => {
  addLog(`点击消息操作: ${message.title}`)
  ElMessage.info(`模拟跳转到: ${message.actionUrl}`)
}

// 发送测试通知
const sendTestNotification = () => {
  addLog(`发送测试通知: ${testForm.value.title}`)
  ElMessage.info('测试通知发送功能（需要后端支持）')
}

// 格式化时间
const formatTime = (timeString) => {
  if (!timeString) return ''
  const date = new Date(timeString)
  return date.toLocaleString('zh-CN')
}

// 获取类型颜色
const getTypeColor = (type) => {
  const colors = {
    contract: 'danger',
    appointment: 'warning',
    house: 'info',
    announcement: 'success'
  }
  return colors[type] || 'info'
}

// 页面初始化
onMounted(() => {
  addLog('系统通知测试页面初始化')
  loadSystemMessages()
  loadUnreadCount()
})
</script>

<style scoped>
.notification-test {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.test-header {
  text-align: center;
  margin-bottom: 30px;
}

.test-header h2 {
  color: #2c3e50;
  margin-bottom: 10px;
}

.test-header p {
  color: #7f8c8d;
}

.section {
  background: white;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.section h3 {
  color: #2c3e50;
  margin-bottom: 15px;
  border-bottom: 2px solid #3498db;
  padding-bottom: 5px;
}

.result-box {
  margin-top: 15px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
}

.message-list {
  margin-top: 15px;
}

.message-item {
  background: white;
  padding: 15px;
  margin-bottom: 10px;
  border-radius: 6px;
  border-left: 4px solid #e9ecef;
}

.message-item.unread {
  border-left-color: #3498db;
  background: #f8f9ff;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.message-title {
  font-weight: 600;
  color: #2c3e50;
}

.message-time {
  font-size: 12px;
  color: #7f8c8d;
}

.message-content {
  color: #5a6c7d;
  margin-bottom: 10px;
  line-height: 1.5;
}

.message-actions {
  display: flex;
  gap: 8px;
}

.empty-state {
  text-align: center;
  color: #7f8c8d;
  padding: 40px;
}

.log-box {
  max-height: 300px;
  overflow-y: auto;
  background: #2c3e50;
  color: #ecf0f1;
  padding: 15px;
  border-radius: 6px;
  font-family: 'Courier New', monospace;
  font-size: 12px;
}

.log-item {
  margin-bottom: 5px;
  display: flex;
  gap: 10px;
}

.log-time {
  color: #3498db;
  min-width: 80px;
}

.log-content {
  flex: 1;
}
</style>
